﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using Facebook;
using Microsoft.Phone.Shell;
using DiscountSharing.FacebookContracts;
using Newtonsoft.Json;
using DiscountSharing.LocalModels;
using System.Collections.ObjectModel;
using System.Linq;

namespace DiscountSharing.LocalControls
{
    public partial class DiscountList : UserControl
    {
        public IDictionary<string, string> QueryContext { private get; set; }
        private string showType;
        private string postQuery;
        private string friendQuery;
        private FacebookClient client;
        private string accessToken;
        private ObservableCollection<Friend> friends;
        private ObservableCollection<Post> posts;
        private ObservableCollection<DiscountElement> discounts;

        public DiscountList()
        {
            InitializeComponent();
            friendQuery = "select uid,name,pic_square,pic from user where uid in "
                + String.Format("(select source_id from stream where source_id in (select uid2 from friend where uid1=me()) and app_id={0})",
                IsolatedStorageSettings.ApplicationSettings["AppID"]);
            postQuery = String.Format("select post_id,source_id,message,updated_time from stream where source_id in (select uid2 from friend where uid1=me()) and app_id={0}",
                IsolatedStorageSettings.ApplicationSettings["AppID"]);
            accessToken = (String)PhoneApplicationService.Current.State["accessToken"];

            Loaded += (o, e) =>
                {
                    if (QueryContext.ContainsKey("show"))
                    {
                        showType = QueryContext["show"];
                        friends = new ObservableCollection<Friend>();
                        posts = new ObservableCollection<Post>();
                        discounts = new ObservableCollection<DiscountElement>();
                        GetFriends();
                    }
                };
        }

        private void GetFriends()
        {
            client = new FacebookClient(accessToken);

            client.GetCompleted += (o, e) =>
            {
                if (e.Error != null)
                {
                    if (((App)App.Current).Friends != null)
                    {
                        friends = ((App)App.Current).Friends;
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(() => MessageBox.Show(e.Error.Message));
                        return;
                    }
                }
                else
                {
                    string result = e.GetResultData().ToString();
                    FriendPage mePage = JsonConvert.DeserializeObject<FriendPage>(result);
                    if (mePage.data.Length != 0)
                    {
                        foreach (FriendContract friend in mePage.data)
                        {
                            friends.Add(new Friend(friend));
                        }
                        ((App)App.Current).Friends = friends;
                    }
                    else
                    {
                        return;
                    }
                }

                GetPosts();
            };

            client.GetAsync("fql",
                new { q = friendQuery });
        }

        private void GetPosts()
        {
            client = new FacebookClient(accessToken);

            client.GetCompleted += (o, e) =>
            {
                if (e.Error != null)
                {
                    if (((App)App.Current).Posts != null)
                    {
                        posts = ((App)App.Current).Posts;
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(() => MessageBox.Show(e.Error.Message));
                        return;
                    }
                }
                else
                {
                    string result = e.GetResultData().ToString();
                    PostPage page = JsonConvert.DeserializeObject<PostPage>(result);
                    if (page.data.Length != 0)
                    {
                        foreach (PostContract post in page.data)
                        {
                            try
                            {
                                posts.Add(new Post(post));
                            }
                            catch
                            {
                                continue;
                            }
                        }
                        ((App)App.Current).Posts = posts;
                    }
                    else
                    {
                        return;
                    }
                }

                Dispatcher.BeginInvoke(() => UpdateUI());
            };

            client.GetAsync("fql",
                new { q = postQuery });
        }

        private void UpdateUI()
        {
            //filtering
            ObservableCollection<Post> uiPosts = posts;
            switch (showType)
            {
                case "all":
                    break;
                case "by_type":
                    break;
                case "by_friend":
                    string friendID = QueryContext["id"];
                    var result = posts.Where(post => post.Writer.ID == friendID);
                    uiPosts = new ObservableCollection<Post>(result);
                    break;
                default:
                    break;
            }

            //bind UI
            discounts.Clear();
            foreach (Post post in uiPosts)
            {
                discounts.Add(new DiscountElement(){ CurrentPost = post });
            }
            List1.DataContext = discounts;
        }
    }
}
